﻿var SortJson=[];//排序用的数组
var is_customer=false;
var MOBILE=true;

//时间的
var calendarDateFormat = myApp.calendar({
    input: '#arrival_time',
     monthNames: ['01'+_(''+_('月')), '02'+_('月'), '03'+_('月'), '04'+_('月'), '05'+_('月'), '06'+_('月'), '07'+_('月'), '08'+_('月') , '09'+_('月') , '10'+_('月'), '11'+_('月'), '12'+_('月')],
    dayNamesShort: [_('日'), _('一'), _('二'), _('三'), _('四'), _('五'), _('六')],
    closeOnSelect:true,
});
var calendarDateFormat = myApp.calendar({
    input: '#receiptarrivalTime',
     monthNames: ['01'+_(''+_('月')), '02'+_('月'), '03'+_('月'), '04'+_('月'), '05'+_('月'), '06'+_('月'), '07'+_('月'), '08'+_('月') , '09'+_('月') , '10'+_('月'), '11'+_('月'), '12'+_('月')],
    dayNamesShort: [_('日'), _('一'), _('二'), _('三'), _('四'), _('五'), _('六')],
    closeOnSelect:true,
});
(function () {
    var dia_stock = {
        init: function () {
        	var args = GetUrlParms();
			if(args["team"]!=undefined){
				 TEAM = args["team"];
			}
            this.bindEvents();
            this.getStock();
        },
        bindEvents: function () {
            var self = this;

            //新增
			$("#add_btn").on("click",function(){
				var link_url="/Team/DiaManagement?team=2";
				if(APP){
					var appJson={};
           			appJson.title=_("裸钻新增");
           			appJson.url=app_url+link_url;
           			YiYi_APP.showNewPage(JSON.stringify(appJson));
				}else{
					location.href=link_url;
				}
			});


            $("#product_table_fixed th").on("click", function () {
                 var sort = $(this).children("i");
                var sort_asc=false;//排序，false为正序，true为反序
                //排序方法
                var sortBy = function (filed, rev, primer) {
				    rev = (rev) ? -1 : 1;
				    return function (a, b) {
				        a = a[filed];
				        b = b[filed];
				        if (typeof (primer) != 'undefined') {
				            a = primer(a);
				            b = primer(b);
				        }
				        if (a < b) { return rev * -1; }
				        if (a > b) { return rev * 1; }
				        return 1;
				    }
				};
                if (sort.length>0) {
                    var iSort = $(this).children("i");
                    var sortName = iSort.attr("data-sort");//排序的字段名
                    var sortDirect = iSort.attr("data-sort-direct");
					$("#stock_body").html('')
                    if (!sortDirect) {
                        sortDirect = "asc";//页面样式
                        SortJson.sort(sortBy(sortName, sort_asc, parseFloat));//排序方法
           				self.bindingInventory(SortJson);//渲染页面
                    }else{
						sortDirect = "";//页面样式
	                    SortJson.sort(sortBy(sortName, true, parseFloat));
           				self.bindingInventory(SortJson);//渲染页面
                    }
                    //iSort.attr("data-sort-direct", sortDirect);
                    iSort.addClass("sort_" + sortDirect);//修改样式

                    $("th i").not(iSort).removeClass("sort_asc").removeClass("sort_desc").removeClass("sort_normal");
                    //$("th i").not(iSort).removeAttr("data-sort-direct");
                    $("th i[data-sort='" + sortName + "']").addClass("sort_" + sortDirect).attr("data-sort-direct", sortDirect);
 				}
            });
            //点击详情关闭
            $("#product_table").on("click", ".stock_detail", function () {
                //$(this).hide();
            });
            //点击行展开详情
            $("#product_table").on("click", "tr.data_tr td", function (event) {
                var td_input = $(this).index();
                if (td_input == 0||td_input == 1) {
                    //勾选框不展开详情
                } else {
                    $(this).parent("tr").next(".stock_detail").slideToggle(0);
                }
            });
            //全选
			$("#th_check_all").on("click",function(){
				var $this=$(this).children().children("span");
				$this.toggleClass("selected")
				if($this.hasClass("selected")){
					$("#stock_body .check_list_box").children("span").addClass("selected");
					$("tbody tr.data_tr").addClass("tr_select_color");
					$(".search_btn_b").css("background-color", primary_color);
			        $(".search_btn_b").attr("disabled", false);
				}else{
					$("tbody tr.data_tr").removeClass("tr_select_color");
					$("#stock_body .check_list_box").children("span").removeClass("selected");
					self.clearBtn();
				}
			});
             //列表的勾选框
			$("#product_table").on("click",".check_rel",function(){
				$(this).children().find("span").toggleClass("selected");
				$(this).parent("tr").toggleClass("tr_select_color");
				//判断是否全选
				var length=$("#stock_body .check_list_box span").length;
				var checkLength=$("#stock_body .check_list_box span.selected").length;
				if(checkLength>0){
					if(length==checkLength){
						$("#th_check_all").find('span').addClass("selected");
					}else{
						$("#th_check_all").find('span').removeClass("selected");
					}
					$(".search_btn_b").css("background-color", primary_color);
			        $(".search_btn_b").attr("disabled", false);
				}else{
					self.clearBtn();
				}
			});
			$("#product_table").on("click","td.check_list_td",function(){
				$(this).prev().find("span").toggleClass("selected");
				$(this).parent("tr").toggleClass("tr_select_color");
				//判断是否全选
				var length=$("#stock_body .check_list_box span").length;
				var checkLength=$("#stock_body .check_list_box span.selected").length;
				if(checkLength>0){
					if(length==checkLength){
						$("#th_check_all").find('span').addClass("selected");
					}else{
						$("#th_check_all").find('span').removeClass("selected");
					}
					$(".search_btn_b").css("background-color", primary_color);
			        $(".search_btn_b").attr("disabled", false);
				}else{
					self.clearBtn();
				}
			});
            //加入购物车
            $("#add_cart_btn").on("click", function () {
                self.multiAddToCart();
            });
            //删除库存
            $("#product_table").on("click",".dia_del_btn",function(){
            	var del_id=$(this).attr("data-id");
            	myApp.confirm(_('您确定要删除该货品吗？'), function () {
					self.delStock(del_id);
				});
            });
            //编辑裸钻
            $("#product_table").on("click",".edit_stock_btn",function(){
            	var url=$(this).attr("data-href");
				if(APP){
					var editJson={};
					editJson.url=app_url+url;
					editJson.title=_("裸钻编辑");
					YiYi_APP.editGoods(JSON.stringify(editJson));
				}else{
					location.href=url;
				}
            });
            //上架
            $(".Shelves_btn").on("click",function(){
            	var shelves_val=$(this).attr("data-value");
            	if(shelves_val==0){//下架
            		$("#Shelves_title").text(_("下架"));
            		$("#Shelves_btn").attr("data-value",0);
            	}else if(shelves_val==1){//上架
            		$("#Shelves_title").text(_("上架"));
            		$("#Shelves_btn").attr("data-value",1);
            	}
            	myApp.popup(".Shelves_box");
            });
            $("#Shelves_btn").on("click",function(){
            	var val=$("input[name='Shelves']:checked").val();
            	var shelves_val=$(this).attr("data-value");
            	self.onStock(val,shelves_val);
            });
            //上架
            $(".product_btn_box span.onstock").on("click",function(){
            	var val=$(this).attr("data-value");
            	self.onStock(val,1);
            });
            //下架
            $(".product_btn_box span.offstock").on("click",function(){
            	var val=$(this).attr("data-value");
            	self.onStock(val,0);
            });
             //跳到证书
            $("#stock_body").on("click","a.cert_link_btn",function(){
            	var link_url=$(this).attr("data-href");
            	if(APP){
            		var appJson={};
           			appJson.title=_("证书");
           			appJson.url=app_url+link_url;
           			YiYi_APP.showNewPage(JSON.stringify(appJson));
            	}else{
            		location.href=link_url;
            	}
            });
            //改变调价选项
            $("#modInputPrice").on("change","input",function(){
            	var val = $(this).attr("data-val");
            	$(".modPrice:eq("+(val-1)+")").show().siblings(".modPrice").hide();
            });
            //批量调价
            $("#bulk_pricing_btn").on("click",function(){
            	$("#_modPrice input.o_modPrice").val("");
            	$("#title_tab span.active").css("background",$.cookie("ThemesColor"));
		    	myApp.popup("#batchDia_box");
            });
             //切换调价
            $("#title_tab").on('click','span',function(){
            	$(this).addClass("active").siblings().removeClass("active");
            	$(this).css("background",$.cookie("ThemesColor")).siblings("span").css("background","#ccc");
            });
            //确定调价
		    $('#batchDia').on('click',function(){
		    	self.ModifyPrice();
		    });
		    //批量修改所在地
            $("#edit_place_btn").on("click",function(){
            	myApp.popup("#ModPlace_box");
            	//所在地
            	if($("#place_box").html()==""){
					var html_Place = '<option value="">' + _("所在地") + '</option>';
					for(var i = 0; i < stock[0].Place.length; i++) {
						html_Place += '<option value="' + stock[0].Place[i][0] + '">' + _(stock[0].Place[i][1]) + '</option>';
					}
					$("#place_box").html(html_Place);
				}
            });
            $("#place_btn").on("click",function(){
            	var val=$("#place_box").val();
            	if(val==""){
            		myApp.alert(_("请选择"));
            	}else{
            		self.batchUpdateDia(1,"#ModPlace_box");
            	}
            });
            //批量修改状态
            $("#edit_status_btn").on("click",function(){
            	myApp.popup("#ModStatus_box");
            	//状态
            	if($("#_batchstatus").html()==""){
					var $Status = '<option value="">' + _("状态") + '</option>';
					for(var i = 0; i < stock[0].Status.length; i++) {
						$Status += '<option value="' + stock[0].Status[i][0] + '">' + _(stock[0].Status[i][1]) + '</option>';
					}
					$("#_batchstatus").html($Status);
                }
            	if($("#stock_body .check_list_box span.selected").length==1){
            		var _val=$("#stock_body .check_list_box span.selected").eq(0).attr("data-comments"); //现货备注
            		var _val_status=$("#stock_body .check_list_box span.selected").eq(0).attr("data-status"); //现货状态
            		$("#ModStatus_Comments").val(_val);
            		$("#_batchstatus").val(_val_status);
            	}
            });
            $("#status_btn").on("click",function(){
            	if($("#_batchstatus").val()==""){
            		myApp.alert(_("请选择"));
            	}else{
            		self.batchUpdateDia(2,"#ModStatus_box");
            	}
            });
            //到货
            $("#edit_arrival_btn").on("click",function(){
            	myApp.popup("#arrival_box");
            });
            $("#arrival_btn").on("click",function(){
          		if($("#arrival_time").val()==""){
          			myApp.alert(_("不能为空"));
          		}else{
          			self.batchUpdateDia(3,"#arrival_box");
          		}
            });
            //付款
            $("#edit_payment_btn").on("click",function(){
            	var ispay=[];
            	var _usd=0;
            	var _rmb=0;
		    	var inventorylistCb = $("#stock_body .check_list_box span.selected");//checked的
	            for (var i = 0; i < inventorylistCb.length; i++) {
	                if(inventorylistCb.eq(i).attr("value")=="0"){//1为已付
	                	ispay.push("0");
	                	_usd+=Number(inventorylistCb.eq(i).attr("data-usd"));
	                	_rmb+=Number(inventorylistCb.eq(i).attr("data-rmb"));
	                }
	            }
	            if(ispay.length==inventorylistCb.length){//未付的个数和选中的个数 一样则全部为未付的
	            	$("#_receipt_usd").text(formatUSDPrice(_usd));
	            	$("#_receipt_rmb").text(formatRMBPrice(_rmb));
	            	self.ReceiptOrders_Js();
	            }else{
	            	myApp.alert(_("请选择未付的产品！"));
	            }

            });
            $("#pay_btn").on("click",function(){
            	self.batchUpdateDia(4,"#pay_box");
            });
            //删除
            $("#del_choose_btn").on("click",function(){
            	myApp.confirm(_("删除后无法恢复，确定要删除吗？"),function(){
            		self.delDia();
            	});
            });
            //买价
            $("#edit_purchase_btn").on("click",function(){
            	myApp.popup("#ModPurchasePrice_box");
            });
            //汇率
            $("#edit_rate_btn").on("click",function(){
            	myApp.popup("#ModRate_box");
            });

			//推荐start
			$("#recommend_btn").on('click',function(){
				$("#title_tab_recommend span.active").css("background",$.cookie("ThemesColor"));
				$('#search_status_box .search_tag').html('')
				myApp.popup("#tag_box");
				getRecommend();
			});
			//切换推荐成品
			$("#title_tab_recommend").on('click','span',function(){
				$(this).addClass("active").siblings().removeClass("active");
				$(this).css("background",$.cookie("ThemesColor")).siblings("span").css("background","#ccc");
				if($("#title_tab_recommend span.active").attr("data-type")==2){
					$("#factor_recommend").hide();
					$("#price_recommend").show();
				}else{
					$("#factor_recommend").show();
					$("#price_recommend").hide();
				}
			});


			$('#recommend_table').on('click','.edit_btn_tag',function(){
				var idEdit=$(this).attr("data-id");
				var shortTag=$(this).attr("data-ShortTag")
				var recommend=$(this).attr("data-Recommend");
				var flagTag=$(this).attr("data-FlagTag");
				if(flagTag==1 || flagTag=="1"){
					$("#_recommend input[type='checkbox']").prop("checked",true);
				}else{
					$("#_recommend input[type='checkbox']").prop("checked",false);
				}
				$("#recommend").val(recommend);
				$("#recommend").attr('data-id',idEdit);
				$("#recommend").attr('data-ShortTag',shortTag);

				$('.addRecommend').val('编辑')
			})
			$("#recommend_inp").on('click',function(){
				self.modifyTag();
			});
			//推荐end

			var aValidate = $("#_receipt").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                	self.payMethod();//付款
                },
                rules: {
                	ArrivalTime: "required",
                    BankID: "required",
                },
                messages: {
                  	ArrivalTime: "",
                    BankID:"",
                }
            });
            //买价
            var validate = $("#_modPurchasePrice").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.batchUpdateDia(5,"#ModPurchasePrice_box");//修改买价
                },
                rules: {
                    factor: "required",
                },
                messages: {
                    factor: "",
                }
            });
            //修改汇率
           var validate = $("#_modRate").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.batchUpdateDia(6,"#ModRate_box");//付款
                },
                rules: {
                    value: "required",
                },
                messages: {
                    value: "",
                }
            });
            //去掉数组里的空值
			Array.prototype.clean = function(deleteValue) {
			  for (var i = 0; i < this.length; i++) {
			    if (this[i] == deleteValue) {
			      this.splice(i, 1);//返回指定的元素
			      i--;
			    }
			  }
			  return this;
			},
			//点击图片icon 
			$("#product_table").on("click",".ImageIcon",function(){
            	var params = {};
            	params.InventoryID = $(this).parent().attr("data-value");
            	params.HasImage = 1
            	self.getImages(params);
            });
            //点击视频icon 
			$("#product_table").on("click",".VideoIcon",function(){
            	var params = {};
            	params.InventoryID = $(this).parent().attr("data-value");
            	params.HasVideo = 1
            	self.getImages(params);
            });
        },
        
        // 获取图片地址
		getImages:function(params){
			var self = this;
			myApp.showIndicator();//显示加载中
			if(TEAM==0){
				var imagesUrl="/Customer/GetImgInfo";//客户端裸钻图片
			}else{
				var imagesUrl="/Team/GetImgInfo";//团队端裸钻图片
			}
            $.ajax({
                url: imagesUrl,//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(params),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    if (_result.msgcode == true) {
                    	myApp.hideIndicator();//隐藏加载中
                    	if(params.HasImage==1){
	                    	var data=_result.msginfo;
							imgs = data.split(",");
							imgArray=[];
					        for (var i=0; i< imgs.length;i++) {
					            if (imgs[i].length > 10) {
					        		var big = imgs[i].replace('800x800', '1920x1920');
					        		imgArray.push(big)
					            }else{
					            	var img_null='/images/no_img.jpg';
					            	imgArray.push(img_null)
					            }
					        }
							//   @*主题色start*@
			                $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
							//  @*主题色end*@
							 //放大图片
							var myPhotoBrowserStandalone = myApp.photoBrowser({
							    photos : imgArray,
							    backLinkText: _('返回'),
							    ofText:"/",
							});
							if(APP){
								var ProductImg={};
								ProductImg['images']=imgArray;
								ProductImg['index']=0;
								YiYi_APP.showImages(JSON.stringify(ProductImg));
							}else{	
								myPhotoBrowserStandalone.open();
						    }	
                    	}else if(params.HasVideo==1){
                    		var firstImg = _result.msginfo.split(',')[0]; 
							if(APP){
								var ProductVideo={};
								ProductVideo.url = firstImg;
								YiYi_APP.showVideo(JSON.stringify(ProductVideo));
							}else{
								myApp.popup('.popup-services');
		                		var videoHtml=[];
								videoHtml.push(
									'<video src="'+firstImg+'" controls="controls"></video>'
								);
								$(".popup-services #PhotoSwipeTarget").html(videoHtml.join(''));
							}
						}
                    } else {
                        myApp.alert(_result.msginfo);
                    }
                    myApp.hideIndicator();//隐藏加载中
                },
		        error: function(XMLHttpRequest, textStatus, errorThrown){
					myApp.alert("网络超时，请重试");
					myApp.hideIndicator();//隐藏加载中
				}
            });
		},
        //批量删除
        delDia:function(){
        	myApp.showPreloader(_("修改中，请稍等!"));
        	var self=this;
        	var inventorylistCb = $("#stock_body .check_list_box span.selected");//checked的
            var _inventoryIDs = "";
            for (var i = 0; i < inventorylistCb.length; i++) {
                if (i == 0)
                    _inventoryIDs += inventorylistCb[i].lang;
                else
                    _inventoryIDs += "," + inventorylistCb[i].lang;
            }
            var submitJson={};
            submitJson.id=_inventoryIDs;

            $.ajax({
                url: "/Team/DelDia",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(submitJson),
                contentType: "application/json; charset=utf-8",
                timeout: 30000, //超时时间：30秒
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    myApp.hidePreloader();//隐藏加载中
                    if (_result.result == true) {
                        myApp.alert(_("成功条目")+"：" + _result.successful.length + _("失败条目")+"："  + _result.failed.length,function(){
							self.getStock();//库存搜索
                        });
                    } else {
                        myApp.alert(_(_result.msginfo));//删除失败
                    }
                },
		        error: function(XMLHttpRequest, textStatus, errorThrown){
					myApp.hidePreloader();//隐藏加载中
					myApp.alert("网络超时，请重试");
				}
            });
        },
        //批量修改
        batchUpdateDia:function(val,lib) {
        	var self=this;
        	myApp.showPreloader(_("修改中，请稍等!"));
            //组装参数start
            var request = {};
            request.filter = {};
            request.filter.ID = [];
            var inventorylistCb = $("#stock_body .check_list_box span.selected");//checked的
            for (var i = 0; i < inventorylistCb.length; i++) {
                request.filter.ID[i] = inventorylistCb[i].lang;
            }

            var submitUrl="/Team/BatchUpdateDia";
            if(val==1){//批量修改所在地
            	request.Place = $("#place_box").val();
            }else if(val==2){//批量修改状态
            	request.Status = $("#_batchstatus").val();
            	var comments=$("#ModStatus_Comments").val();
	           if(inventorylistCb.length==1){
	           		request.comments=comments;
	           	}else{
	           		if(comments!=""){
	           			request.comments=comments;
	           		}
	           	}
            }else if(val==3){//到货
            	request.ArrivalTime=$("#arrival_time").val();
            	var submitUrl="/Team/UpdateArrivalTime";
            }else if(val==4){//付款
            	request.ReceiptStatus=$("input[name='payment']:checked").val();
            	var submitUrl="/Team/UpdateReciptStatus";
            }else if(val==5){//修改买价
            	request.factor = $("#_purchasePrice").val();
            	request.field="PurchaseUSDPerGrain";
            	var submitUrl="/team/UpdateStockingPrice";
            }else if(val==6){//修改汇率
            	request.value = $("#mod_rate").val();
            	request.field="PurchaseExchange";
            	var submitUrl="/team/UpdatesStockingPurchaseExchange";
            }
            $.ajax({
                url: submitUrl,//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(request),
                contentType: "application/json; charset=utf-8",
                timeout: 30000, //超时时间：30秒
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    myApp.hidePreloader();
                    if (_result.result == true || _result.msgcode==true) {
                       	myApp.closeModal(lib);
                    	myApp.alert(_("修改成功！"),function(){
							self.getStock();//库存搜索
                    	});

                    } else {
                        myApp.alert(_(_result.msg));
                    }
                },
	            error: function(XMLHttpRequest, textStatus, errorThrown){
					myApp.hidePreloader();//隐藏加载中
					myApp.alert("网络超时，请重试");
				},
            });
        },

        //清空按钮的状态
        clearBtn:function(){
			$(".search_btn_b").css("background-color","#a1a1a1");
			$(".search_btn_b").attr("disabled",true);
		},
        //上架
        onStock:function(val,num){
        	var self=this;
        	if(num==0){//下架
        		var valTypeText=_("下架");
        		var stock_url="/Team/OffShelves";
        	}else if(num==1){//上架
        		var valTypeText=_("上架");
        		var stock_url="/Team/OnShelves"
        	}

        	if(val==2){
        		var valText=_("确定")+valTypeText+_("全部裸钻(白+彩)？");
        		var params="";
        	}else if(val==0){
        		var valText=_("确定")+valTypeText+_("全部白钻？");
        		var params={};
        		params.IsFancy = 0; 
        	}else if(val==1){
        		var valText=_("确定")+valTypeText+_("全部彩钻？");
        		var params={};
        		params.IsFancy = 1; 
        	}else if(val==3){//勾选的
        		var valText=_("确定")+valTypeText+_("选中的产品？");
        		var params={};
        		params.filter={};
        		params.filter.ID=[];
        		var inventorylistCb = $("#stock_body .check_list_box span.selected");//checked的
        		if(inventorylistCb.length<1){
        			myApp.alert(_("请勾选！"));
        			return false;
        		}
	            for (var i = 0; i < inventorylistCb.length; i++) {
	                params.filter.ID[i] = inventorylistCb[i].lang;
	            }
	            params.OnShelves=num;
        		var stock_url=num==1?"/Team/OnStocksBatch":"/Team/OffStocksBatch";
        	}
        	params.UserID=UserID;
	        params=JSON.stringify(params);
        	myApp.confirm(valText,function() {
        		myApp.showPreloader(_("修改中，请稍等!"));
                $.ajax({
                    url: stock_url,//提交地址
                    type: "POST",//提交方式
                    data: params,
                    contentType: "application/json; charset=utf-8",
                    timeout: 30000, //超时时间：30秒
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象
                        myApp.hidePreloader();//隐藏加载中
                        $(".Shelves_box").hide();
                        if (_result.msgcode == true) {
                            myApp.alert(_(_result.msginfo),function(){
								self.getStock();//库存搜索
                            });
                        } else {
                            myApp.alert(_(_result.msginfo));
                        }
                    },
			        error: function(XMLHttpRequest, textStatus, errorThrown){
						myApp.hidePreloader();//隐藏加载中
						myApp.alert("网络超时，请重试");
					}
                });
            });
        },
        //删除库存
		delStock:function(del_id){
			var self=this;
			var params={};
			params.id=del_id;
			$.ajax({
				url: "/Team/DelDia",//提交地址
				type: "POST",//提交方式
				data: JSON.stringify(params),
				contentType: "application/json; charset=utf-8",
				success: function (result) {
					var _result = eval('(' + result + ')');//eval()解析单个json对象
					if (_result.result == true) {
						myApp.alert(_("删除成功！"));
						self.getStock();//库存搜索
					} else {
						myApp.alert(_(_result.msginfo));//删除失败
					}
				}
            });
		},

		//批量修改推荐
		modifyTag:function(){
			var self=this;
			var request = {};
			request.filter = {};
			request.filter.ID = [];
			var inventorylistCb = $("#stock_body .check_list_box span.selected");
			for (var i = 0; i < inventorylistCb.length; i++) {
				request.filter.ID[i] = inventorylistCb[i].lang;
			}
			if($('#recommend_form input[name="Recommend"]:checked').val()>0){
				request.Tag = $('#recommend_form input[name="Recommend"]:checked').val();
			}else{
				request.Tag=0;
			}
			request.GoodsType=1;
			$.ajax({
				url: "/Team/ModifyProducts",//提交地址
				type: "POST",//提交方式
				data: JSON.stringify(request),
				contentType: "application/json; charset=utf-8",
				timeout: 30000, //超时时间：30秒
				success: function (result) {
					var data=JSON.parse(result);
					myApp.hidePreloader();//隐藏加载中
					if(data.result==true){
						toast(_("修改成功"));
						$("#tag_box").hide();
						self.getStock();//库存搜索
					}else{
						myApp.alert(_("修改失败"));
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					myApp.hidePreloader();//隐藏加载中
					myApp.alert("网络超时，请重试");
				}
			});
		},
        //获取库存
        getStock: function (pageIndex,pageSize,clear_dia) {
            var self = this;


           	 	myApp.showIndicator();//显示加载中

             var params = PARAMS;
            if(params==null){
         		params={};
         		params.IsFancy=0;
         		params.limit=5000;
     			params.useDict=true;
         	}else{
         		//原货号
         		if(params.OriginSN!=undefined && params.OriginSN!=""){
	         		var OriginSNValArray=params.OriginSN.split(" ");
					OriginSNValArray.clean("");
					params.OriginSN=OriginSNValArray;
				}
         		//证书号
         		if(params.CertNo!=undefined && params.CertNo!=""){
					var CertNoValArray=params.CertNo.split(" ");
					CertNoValArray.clean("");
					params.CertNo=CertNoValArray;
				}
         	}
         	if(TEAM==2){
         		params.IsStock=1;//现货
         	}else{
         		params.OnShelves = "1";
         	}
			params.limit=5000;
			params.UserID=UserID;

            //获取排序
            var requestJson = JSON.stringify(params);
            $.ajax({
                url: "/Team/GetInventoryInfos",
                data: requestJson,
                type: "post",
                contentType: "application/json; charset=utf-8",
                timeout: 30000, //超时时间：30秒
                success: function (result) {
					// myApp.hideIndicator();//隐藏加载中
                   var _result = eval('(' + result + ')');//eval()解析单个json对象
		            var tableTbody = $("#stock_body");
		            self.clearBtn();
		            $("#th_check_all").find("span").removeClass("selected");
		            //获取库存成功
		            if (_result["msgcode"] == true) {
		               if (_result["data"].Data.length== 0) {
		                    //无结果
		                    var tr = "";//单行
		                    var tds = "<td colspan='12' style='text-align:center;color:red'>"+_("没有符合条件的结果")+"</td>";// 多列合成一列并居中
		                    tr = "<tr>" + tds + "</tr>";//将多列加到一行
		                    tableTbody.html(tr);//加入到id为customer的table的tbody中

		               } else {
						   if(clear_dia){
							   $("#stock_body").html('');
						   }
				            _result = _result["data"].Data;//object
				            SortJson = _result;
						   	// SortJson = SortJson.concat(_result); //合并数组
		                    self.bindingInventory(_result);//绑定白钻
		                    $("body").scrollTop(0);
                   		}
                	}else {
		            //获取库存失败
		            var tr = "";//单行
		            var tds = "<td colspan='12' style='text-align:center;color:red'>" + _(_result["msginfo"]) + "</td>";// 多列合成一列并居中
		            tr = "<tr>" + tds + "</tr>";//将多列加到一行
		            tableTbody.html(tr);//加入到id为customer的table的tbody中
		        }

               		myApp.hideIndicator();//隐藏加载中


               	},
               	error: function(XMLHttpRequest, textStatus, errorThrown){
					myApp.hideIndicator();//隐藏加载中
					myApp.alert("网络超时，请重试");
				},
            });
        },

        //绑定数据
        bindingInventory: function (_result) {
        	var ordering_SourceDiscountReturn= ShowColumn("ordering_SourceDiscountReturn");
        	var ordering_SourceDolarPerCarat= ShowColumn("ordering_SourceDolarPerCarat");
        	var ordering_SourceDolarPerGrain= ShowColumn("ordering_SourceDolarPerGrain");
        	var ordering_Supplier = ShowColumn("ordering_Supplier");//供应商
        	var ordering_RMBPerGrain = ShowColumn("ordering_RMBPerGrain");//￥/Pcs
        	var ordering_RMBPerCarat = ShowColumn("ordering_RMBPerCarat");//￥/Ct
        	var ordering_DolarPerGrain = ShowColumn("ordering_DolarPerGrain");//$/Pcs

        	var ordering_DolarPerCarat = ShowColumn("ordering_DolarPerCarat");//$/Ct
        	var ordering_DiscountReturn = ShowColumn("ordering_DiscountReturn");//退点
        	var ordering_Rapnet = ShowColumn("ordering_Rapnet");//Rap
           var tableTbody = $("#stock_body");
            var trs = "";//多行数据
            for (var i = 0; i < _result.length; i++) {
                if (_result[i].IsFancy == 1 ) {
                    $(".fancy_show").show();
                    $(".white_show").hide();
                } else {
                	if(ordering_DiscountReturn ==1 || RoleID == 1){
                    	$(".white_show").show();
					}
                    $(".fancy_show").hide();
                }

                if(ordering_RMBPerGrain ==1 || RoleID == 1){
					$('.total_show').show();
				}else{
					$('.total_show').hide();
				}

				var colNum='';
				if((ordering_DiscountReturn==1 && ordering_RMBPerGrain ==1) || RoleID == 1){
					colNum=12;
				}else{
					if(ordering_DiscountReturn==1 ||　ordering_RMBPerGrain ==1　|| RoleID ==1){
						colNum=9;
					}else{
						colNum=8
					}
				}

                var tds = "";//多列
                var tr = "";//单行
                var tr_div = "";
                var data=_result[i];
                tds += "<td class='check_rel'>"+
                "<div class='check_list_box'><span class='checkbox' value='"+data.ReceiptStatus+"' name='checkbox' lang='" +
                data.ID + "' data-usd='"+formatUSDPrice(data.DolarPerGrain)+"' data-rmb='"+formatRMBPrice(data.RMBPerGrain)+
                "' data-comments='"+data.Comments+"' data-status='"+data.Status+"' data-Tag='"+data.Tag+"'></span></div>";
//              "<input type='checkbox' value='check[i]' name='checkbox' lang='" + data.InventoryID + "'/><div class='checkbox_fu'></div></td>";
                tds += "<td class='check_list_td'>" + data.Weight + "</td>";
                if (data.IsFancy == 1) {
                    tds += "<td>" +ColorFormat(data.Color) + "</td>";
                } else {
                    tds += "<td>" + data.Color + "</td>";
                }
                tds += "<td>" + data.Clarity + "</td>";
                tds += "<td>" + data.Cut + "</td>";
                tds += "<td>" + data.Polish + "</td>";
                tds += "<td>" + data.Symmetry + "</td>";
                tds += "<td>" + data.Fluorescence + "</td>";
                 if (data.IsFancy == 0) {
                 	if(ordering_DiscountReturn==1 || RoleID == 1)
						tds += "<td>" + ValueFormat(data.DiscountReturn) + "</td>";
                }else{
                	 if($.cookie("CurrentSet") == 2){ //美金
                	 	if(ordering_DolarPerCarat==1 || RoleID == 1)
	               			tds += "<td>"+formatUSDPrice(data.DolarPerCarat)+"</td>";
	               	}else{ //全局0和人民币1显示美金
	               		if(ordering_RMBPerCarat==1 || RoleID == 1)
	               			tds += "<td>"+formatRMBPrice(data.RMBPerCarat)+"</td>";
	               	}
                }
				var rate=Number($.cookie("DiasRate"))

                if($.cookie("CurrentSet") == 2){ //美金
                	if(ordering_DolarPerGrain==1 || RoleID == 1)
               			// tds += "<td style='font-weight:bold' class=''>" + formatUSDPrice(data.DolarPerGrain) + "</td>";//四舍五入
               			tds += "<td style='font-weight:bold' class=''>" + formatUSDPrice(data.SourceDolarPerGrain) + "</td>";//四舍五入
               	}else{ //全局0和人民币1显示人民币
               		if(ordering_RMBPerGrain==1 || RoleID == 1)
               			// tds += "<td style='font-weight:bold' class='td_second'>" + formatRMBPrice(data.RMBPerGrain) + "</td>";//四舍五入
               			tds += "<td style='font-weight:bold' class='td_second'>" + formatRMBPrice(data.SourceDolarPerGrain*rate) + "</td>";//四舍五入
               	}
                tr += "<tr class='data_tr'>" + tds + "</tr>";//将多列加到一行
                tr_div="<tr class='stock_detail'><td  colspan='"+colNum+"'>"+
                "<div class='detail_left'>"+
                	"<i><b>"+_("形状")+"：</b>"+GetText("stocks",1,data.Shape,"Shape")+"</i>"+
               	 	"<i><b>"+_("奶油")+"：</b>" + MilkyFormat(data.Milky) + "</i>"+
               	 	"<i><b>"+_("色调")+"：</b>" + HueFormat(data.Hue) + "</i>"+
               	 	"<i><b>"+_("心箭")+"：</b>" + HAFormat(data.HA) + "</i>"+
               	 	"<i onclick='showTotalWord(this)'><b>"+_("黑点")+"：</b>" + BlackDefectFormat(data.BlackDefect) + "</i>" +
                	"<i onclick='showTotalWord(this)'><b class='custrom'>"+_("瑕疵")+"：</b><span>" + OtherDefectFormat(data.OtherDefect) + "</span></i>"+
                "</div>" +
                "<div class='detail_middle'>";
                if(ordering_RMBPerCarat==1 || RoleID == 1)
                	tr_div+="<i><b>"+_("单价")+"：</b>" + formatRMBPrice(data.RMBPerCarat) + "</i>";

                	tr_div+="<i><b class='custrom'>"+_("类型")+"：</b>" + CertTypeFormat(data) + "</i>";
                	tr_div+="<i onclick='showTotalWord(this)'><b>"+_("货号")+"：</b>" + data.SN + "</i>" +
                	"<i><b>"+_("状态")+"：</b>" + GetText("stocks",1,data.Status,"Status") + "</i>"+
                	"<i><b>"+_("所在地")+"：</b>" + GetText("stocks",1,data.Place,"Place") + "</i>" ;
                	if(ordering_Rapnet==1 || RoleID == 1)
                		tr_div+="<i><b>"+_("国际报价")+"：</b>" + data.Rapnet + "</i>";
                "</div>" +
                "<div class='detail_right'>";
                if(ordering_Supplier==1 || RoleID == 1){
                	tr_div+="<i><b class='custrom' style='width:auto'>"+_("供应商")+"：</b>"+
	                "<span style='color:red' onclick='Contact_Js(this)' value="+data.SupplierCode+">" + data.Supplier + "</span></i>";
	            }
                if(ordering_SourceDiscountReturn==1 || RoleID == 1){
                	tr_div+="<i><b>"+_("原退点")+"：</b>" + data.SourceDiscountReturn + "</i>";
                }
                if(ordering_SourceDolarPerCarat==1 || RoleID == 1){
                	tr_div+="<i><b>"+_("原单价")+"：</b>" + formatUSDPrice(data.SourceDolarPerCarat) + "</i>";
                }
                	tr_div+="<i><b class='custrom'>"+_("尺寸")+"：</b><span>" + data.Measurement + "</span></i>" ;
                if(ordering_SourceDolarPerGrain==1 || RoleID == 1){
                	tr_div+="<i><b>"+_("原总价")+"：</b>" + formatUSDPrice(data.SourceDolarPerGrain) + "</i>";
                }
                tr_div+="<i><b class='custrom'>"+_("上传")+"：</b><span>" + CovertTime(data.UpdateTime) + "</span></i>"+
                "</div>"+
                "</td></tr>";
                var p_price = calcPercent1Price(data.SourceDiscountReturn, data.SourceDolarPerGrain); //100/1   美金粒
                //采退点
                if(data.PurchaseUSDPerGrain!=0){
                	var c=data.PurchaseUSDPerGrain/p_price-100;
                }else{
                	var c=data.PurchaseDiscountReturn;
                }
//              var c = (data.PurchaseDiscountReturn == 0 ? Math.round(data.SourceDiscountReturn) : data.PurchaseDiscountReturn);
                //采$
				if (data.PurchaseDiscountReturn==0)
                    var e =data.PurchaseUSDPerGrain;//采$
                else
                    var e = (p_price * (100 + (data.PurchaseDiscountReturn))).toFixed(3);//采$
//              if (data.PurchaseDiscountReturn == 0)
//                  var e = Math.round(PurchaseUSDPerGrainFormat(data.PurchaseUSDPerGrain) == "" ? data.SourceDolarPerGrain : PurchaseUSDPerGrainFormat(data.PurchaseUSDPerGrain));
//              else
//                  var e = Math.round(p_price * (100 +data.PurchaseDiscountReturn));
                tr_manage_div="<tr class='stock_detail'><td  colspan='"+colNum+"'>"+
                "<div class='detail_left' style='width:50%'>"+
					"<i onclick='showTotalWord(this)'><b class='custrom'>"+_("货号")+"：</b><span>" + data.SN + "</span></i>" +
                	"<i><b>"+_("形状")+"：</b>"+GetText("stocks",1,data.Shape,"Shape")+"</i>"+
               	 	"<i><b>"+_("奶油")+"：</b>" + MilkyFormat(data.Milky) + "</i>"+
               	 	"<i><b>"+_("色调")+"：</b>" + HueFormat(data.Hue) + "</i>"+
               	 	"<i><b>"+_("心箭")+"：</b>" + HAFormat(data.HA) + "</i>"+
               	 	"<i onclick='showTotalWord(this)'><b class='custrom'>"+_("黑点")+"：</b><span>" + BlackDefectFormat(data.BlackDefect) + "</span></i>" +
               	 	"<i onclick='showTotalWord(this)'><b class='custrom'>"+_("尺寸")+"：</b><span>" + data.Measurement + "</span></i>" +
                	"<i onclick='showTotalWord(this)'><b class='custrom'>"+_("瑕疵")+"：</b><span>" + OtherDefectFormat(data.OtherDefect) + "</span></i>"+
                	"<i><b>"+_("证书")+"：</b>" + CertTypeFormat(data) + "</i>"+
                	"<i onclick='showTotalWord(this)'><b class='custrom'>"+_("证书号")+"：</b><span>" + NullFormat(data.CertNo) + "</span></i>"+
                	"<i><b>"+_("上/下架")+"：</b><ins style='color:red;text-decoration:none;'>" + (data.OnShelves==1?_("上架"):_("下架")) + "</ins></i>"+
                	"<i><b class='custrom'>"+_("上传")+"：</b>" + YearDateFormat(data.UpdateTime) + "</i>";

                	// tr_manage_div+="<i class='CurrentRMB'><b>￥/Ct：</b>" + formatRMBPrice(data.RMBPerCarat) + "</i>";
                	// tr_manage_div+="<i class='CurrentRMB'><b>￥/Pcs：</b>" + formatRMBPrice(data.RMBPerGrain) + "</i>";
                	// tr_manage_div+="<i class='CurrentUSD'><b>$/Ct：</b>" + formatUSDPrice(data.DolarPerCarat) + "</i>";
                	// tr_manage_div+="<i class='CurrentUSD'><b>$/Pcs：</b>" + formatUSDPrice(data.DolarPerGrain) + "</i>";
                	tr_manage_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("备注")+"：</b><span>" + NullFormat(data.Comments) + "</span></i>";
                	tr_manage_div+="<i><b>"+_("Rap")+"：</b>" + data.Rapnet + "</i>";
                	tr_manage_div+="<i data-value='"+data.ID+"'><b>"+_("图片")+"：</b>" + GetImgHd(data) + "</i>";
                	tr_manage_div +="</div>"
                    tr_manage_div +="<div class='detail_right' style='width:50%'>";
                	tr_manage_div += "<i><b>" + _("状态") + "：</b>" + GetText("stocks", 1, data.Status, "Status") + "</i>";
                	tr_manage_div+="<i><b>"+_("所在地")+"：</b>" + GetText("stocks",1,data.Place,"Place")+ "</i>";
                	// tr_manage_div+="<i><b class='custrom' style='width:auto'>"+_("供应商")+"：</b>"+
	                "<span style='color:red' onclick='Contact_Js(this)' value="+data.Supplier+">" + data.Supplier + "</span></i>";
                	tr_manage_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("原货号")+"：</b><span>" + data.OriginSN + "</span></i>";
                	tr_manage_div+="<i><b>"+_("原退点")+"：</b>" + data.SourceDiscountReturn + "</i>";
//              	"<i><b>"+_("原")+"$/Ct：</b>" + Math.round(data.SourceDolarPerCarat) + "</i>"+
                	tr_manage_div+="<i class='CurrentUSD'><b>"+_("原")+"$：</b>" + formatUSDPrice(data.SourceDolarPerGrain) + "</i>";
                	tr_manage_div += "<i><b>" + _("采退点") + "：</b>" + DiscountReturnFormat(c) + "</i>";
                	tr_manage_div += "<i class='CurrentUSD'><b>" + _("采") + "$：</b>" + formatUSDPrice(e) + "</i>";
                	tr_manage_div+="<i><b class='custrom' style='width:auto'>"+_("采供应商")+"：</b>";
                	tr_manage_div+="<span style='color:red' onclick='Contact_Js(this)' value="+data.PurchaseSupplier+">" + partShowSubstring(data.PurchaseSupplier) + "</span></i>";
                	tr_manage_div+="<i><b>"+_("买汇率")+"：</b>" +data.PurchaseExchange + "</i>";
                	tr_manage_div+="<i class='CurrentRMB'><b>"+_("买")+"RMB：</b>" +formatRMBPrice(data.PurchaseRMB) + "</i>";
                	tr_manage_div+="<i onclick='showTotalWord(this)'><b class='custrom'>"+_("采购人")+"：</b><span>" +returnPurchaseAgent(data)+ "</span></i>";
                	if(data.PurchaseTime){
                        tr_manage_div+="<i><b style='width:auto'>"+_("买入时间")+"：</b>" +YearDateFormat(new Date(GetDateDiff(data.PurchaseTime)).getTime())+ "</i>";
					}else {
                        tr_manage_div+="<i><b style='width:auto'>"+_("买入时间")+"：</b>-</i>";
					}
					if(data.ArrivalTime){
                    	tr_manage_div += "<i><b style='width:auto'>" + _("到货时间") + "：</b>" + YearDateFormat(new Date(GetDateDiff(data.ArrivalTime)).getTime()) + "</i>";
				    }else{
                    	tr_manage_div += "<i><b style='width:auto'>" + _("到货时间") + "：</b>-</i>";
					}
                	tr_manage_div += "<i><b>" + _("付款") + "：</b>" + formatReceiptStatus(data.ReceiptStatus) + "</i>";
                	tr_manage_div += "<i><b>" + _("台宽比") + "：</b>" + TableFormat(data.TablePct) + "</i>";
                	tr_manage_div += "<i><b>" + _("全深比") + "：</b>" + DepthFormat(data.DepthPct) + "</i>";

                "</div>"+
                "<div class='stock_btn_box'><div class='modify_btn'>"+
                	"<a class='edit_stock_btn' href='#' data-href='/Team/DiaManagement?ID="+data.ID+"&type=1'>"+_("修改")+"</a></div>"+
                	"<div class='dia_del_btn' data-id="+data.ID+">"+_("删除")+"</div></div>"+
                "</td></tr>";
                if(TEAM==2){
               		 trs += tr+tr_manage_div;//将单行加到多行
               	}else{
               		 trs += tr+tr_div;//将单行加到多行
               	}

            }
               tableTbody.html(trs);//加入到id为customer的table的tbody中
              currentShow();  //币种设置
        },
        //付款账户
        ReceiptOrders_Js:function(){
        	 //仅管理员1 和 财务2
		    if (RoleID == 1 || RoleID == 2 || RoleID == 6) {
		        myApp.popup("#pay_box");
		        var requestJson={};
		        requestJson.Status=1;
		        requestJson.CheckResult=1;
		        if($.cookie("CurrentSet") == 2){
		        	requestJson.Currency=2;
		        }
		        if($.cookie("CurrentSet") == 1){
		        	requestJson.Currency=1;
		        }
		        //付款账户
		        $.ajax({
		            url: "/Team/GetBankList",//提交地址
		            type: "POST",//提交方式
		            data: JSON.stringify(requestJson),
		            contentType: "application/json; charset=utf-8",
		            success: function (result) {
		                var _result = eval('(' + result + ')');//eval()解析单个json对象

		                var options = "";
		                options += '<option value="">'+_("选择账户")+'</option>';
		                for (var i = 0; i < _result.length; i++) {
		                    options += '<option value="' + _result[i].BankID + '" data-type="'+_result[i].Currency+'">【' + _result[i].BankName + '】' + _result[i].BankBalance + '' + CurrencyFormat(_result[i].Currency) + '</option>';
		                }
		                $("#_receiptBankID").html("");
		                $("#_receiptBankID").html(options);
		            }
		        });
		    } else {
		        myApp.alert(_("【付款】禁用"));
		    }
        },
        //付款
        payMethod:function(){
        	myApp.showPreloader(_("修改中，请稍等!"));
        	var self=this;
       		var request = {};
            request.filter = {};
            request.filter.ID = [];
			var inventorylistCb = $("#stock_body .check_list_box span.selected");//checked的
            for (var i = 0; i < inventorylistCb.length; i++) {
                request.filter.ID[i] = inventorylistCb[i].lang;
            }
            request.ReceiptStatus=1;//已付状态
            request.ApplyID=UserID;//操作人
            var currency=$("#_receiptBankID option:checked").attr("data-type");//1人民币 2美金
            request.Currency=currency;
            if(currency==1){//人民币
            	request.TotalMoney=Number($("#_receipt_rmb").text());//人民币价格
            }else {
            	request.TotalMoney=$("#_receipt_usd").text();//美金价格
            }
            request.ArrivalTime=$("#receiptarrivalTime").val();
            request.BankID=$("#_receiptBankID").val();
            $.ajax({
            	type:"post",
            	url:"/Team/UpdateReciptStatus",
            	data:JSON.stringify(request),
            	contentType:"application/json; charset=utf-8",
            	timeout: 60000, //超时时间：30秒
                success: function (result) {
                	var data=eval('('+result+')');
                	myApp.hidePreloader();//隐藏加载中
                	if(data.msgcode==true){
                		$("#pay_box").hide();
                		myApp.alert(_(data.msginfo));
						self.getStock();//库存搜索
                	}else{
                		myApp.alert(_(data.msginfo));
                	}
                },
		        error: function(XMLHttpRequest, textStatus, errorThrown){
					myApp.hidePreloader();//隐藏加载中
					myApp.alert("网络超时，请重试");
				}
            });
        },
        //调价
		ModifyPrice: function(){
			myApp.showPreloader(_("修改中，请稍等!"));
			var self = this;
			var request = {};
			var Ids = [];
			var allPrice = $("#title_tab span.active").attr("data-type");

            if($(".modInputPrice input:checked").attr("data-val")==1){
            	request.field = "OriginDiscountReturn";
            	if(allPrice=="2"){
            		request.value = $.trim($("#OriginDiscountReturn").val());//field:对应的值
            	}else{
            		request.operand = $.trim($("#OriginDiscountReturn").val());//field:对应的值
            	}
            }else if($(".modInputPrice input:checked").attr("data-val")==2){
            	request.field = "OriginUSDPerGrain";
            	if(allPrice=="2"){
            		request.value = $.trim($("#OriginUSDPerGrain").val());
            	}else{
            		request.operand = $.trim($("#OriginUSDPerGrain").val());
            	}

            }else if($(".modInputPrice input:checked").attr("data-val")==3){
            	request.field = "OriginUSDPerCarat";
            	if(allPrice=="2"){
            		request.value = $.trim($("#OriginUSDPerCarat").val());
            	}else{
            		request.operand = $.trim($("#OriginUSDPerCarat").val());
            	}

            }
			var inventorylistCb = $("#stock_body .check_list_box span.selected");//checked的
            for (var i = 0; i < inventorylistCb.length; i++) {
                Ids.push(inventorylistCb[i].lang);
            }

            //是否全选
			if($(".check_rel span[name='checkbox']").size()>=500&&$(".check_rel span[name='checkbox']").size()==$(".check_rel span[name='checkbox'].selected").size()){
                request.filter={};
			}else{
            	request.ID = Ids;
			}
            var oDiscount = $("#OriginDiscountReturn").val();
            var oPerGrain = $("#OriginUSDPerGrain").val();
            var oPerCarat = $("#OriginUSDPerCarat").val();

            if((oDiscount!="" && $.trim(oDiscount)!="") || (oPerGrain!="" && $.trim(oPerGrain)!="") || (oPerCarat!="" &&  $.trim(oPerCarat)!="")){
	            $.ajax({
	            	type:"post",
	            	url:"/team/BatchDia",
	            	data:JSON.stringify(request),
	            	contentType:"application/json; charset=utf-8",
	            	timeout: 30000, //超时时间：30秒
	                success: function (result) {
		              	var data=eval('('+result+')');
		              	myApp.hidePreloader();//隐藏加载中
		              	if(data.result==true){
		              		toast(_("修改成功"));
		              		$("#batchDia_box").hide();
							self.getStock();//库存搜索
		              	}else{
		              		myApp.alert(_("修改失败"));
		              	}
	                },
			        error: function(XMLHttpRequest, textStatus, errorThrown){
						myApp.hidePreloader();//隐藏加载中
						myApp.alert("网络超时，请重试");
					}
	            });
            }else{
            	myApp.hidePreloader();//隐藏加载中
            	myApp.alert(_("请填写数据"));
            }
		}
    }

    dia_stock.init();
}());

// 获取图片和视频
function GetImgHd(data){
	var str = "";
	if(data.HasImage==1){
        str +='<img alt="图片" src="/images/imageIcon.png" class="ImageIcon" />';
    }
	if(data.HasVideo==1){
		str+='<img alt="视频" src="/images/videoIcon.png" class="VideoIcon" />'
	}
	return str;
}
 //获取权限
// function ShowColumn(columnName){
//     var roles = UserRoles.split(',');
//     if (roles != null)
//     {
//         for (var i = 0; i < roles.length; i++) {
//             if (roles[i] == "."+columnName) {
//                 return true;
//             }
//         }
//         return false;
//     }
// }



//采购人
function returnPurchaseAgent(data){
	var $div="";
	if (list.msgcode && data.PurchaseAgent!=undefined && data.PurchaseAgent!="") {
        $div= list.msginfo[data.PurchaseAgent]; //新增：采购人
   }else {
        $div= "-"; //新增：采购人
    }
   if($div==undefined){
   		$div= "-"; //新增：采购人
   }
    return $div;
}

//单击变色
function click_change_tr_color(me) {
    $(me).next(".stock_detail").slideToggle(0);
}

//返回彩钻的首字母
function ColorFormat(wrods) {
    var ws = wrods.split(' ');
    var lw = "";
    for (var i = 0; i < ws.length; i++) {
        lw = lw + ws[i].substring(0, 1).toUpperCase()
    }
    if (lw == "")
        return wrods
    return lw

}
function formatReceiptStatus(val){
	if(val==0){
		return _("未支付");
	}else if(val==1){
		return _("已支付");
	}
}

//计算100、1
function calcPercent1Price(dd, pp) {
	var d=Number(dd);
	var p=Number(pp);
    var disc = (100 + d);
    if(disc!=0){
    	var sp = p / disc;
    }else{
    	var sp=0;
    }
    return Number(sp);
}
//      买入RMB格式化
function PurchaseRMBFormat(PurchaseRMB) {
    var pur = Math.round(PurchaseRMB);
    if (pur == 0 || undefined) {
        return "";
    } else {
        return pur;
    }
}
//      采$/ct格式化
function PurchaseUSDPerCaratFormat(PurchaseUSDPerCarat) {
    var pur = Math.round(PurchaseUSDPerCarat);
    if (pur == 0 || undefined) {
        return "";
    } else {
        return pur;
    }
}

//      采$格式化
function PurchaseUSDPerGrainFormat(PurchaseUSDPerGrain) {
    var pur = Math.round(PurchaseUSDPerGrain);
    if (pur == 0 || undefined) {
        return "";
    } else {
        return pur;
    }
}
//供应商联系方式
function Contact_Js(me) {
	myApp.showIndicator();
    $.ajax({
        url: "/Team/ContactSupplier",//提交地址
        type: "POST",//提交方式
        data: "{'SupplierCode':'" + me.getAttribute("value") + "'}",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false) {
                myApp.alert(_result.msginfo);
            } else {
                var _result = eval('(' + _result + ')');//再次解析_result

                if (_result.result == true) {
                    $("#_company").val(_result.Company);
                    $("#_shortName").val(_result.ShortName);
                    $("#_website").val(_result.Contact.Website);//json.json.json
                    $("#_qq").val(_result.Contact.QQ);
                    $("#_name").val(_result.Contact.Name); //Telephone
                    $("#_telephone").val(_result.Contact.Telephone);
                    $("#_rapid").val(_result.Contact.RapID);
                    //$("#_skype").val(_result.Contact.Skype);
                    if (_result.Contact.Skype != "") {
                        $("#_skype").html("<b style='font-size:20px;' title='点击和" + _result.Contact.Skype +
                        "聊天'><span><img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1489148014986&di=253cba520b4b4c293c60f95cabd708db&imgtype=0&src=http%3A%2F%2Fimg.download.pchome.net%2F3p%2F7b%2Flogo.jpg' style='border: none;width:20px;height:20px;' /></span><label>" +
                        _result.Contact.Skype + "</label></b>");//点击打开Skype
                    } else {
                        $("#_skype").html("");
                    }
                    $("#_email").val(_result.Contact.Email);
                    $("#_wechat").val(_result.Contact.WeChat);
                    $("#_mobilephone").val(_result.Contact.MobilePhone);
                    $("#_address").val(_result.Address.Country + "-" + _result.Address.State + "-" + _result.Address.City);//中国-广东-深圳
                    myApp.popup(".Contact_box");
//                  $(".Contact_box").show();
                } else {
                    //暂无联系方式
                    myApp.alert(_("该供应商暂无联系方式"));
                }
            }
            myApp.hideIndicator();
        }
    });
}
//兼容IOS时间显示
function GetDateDiff(DiffTime) {
    //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
    Time = DiffTime.replace(/\-/g, "/");
    return Time;
}

//格式化台宽比
function TableFormat(rapnetValue) {
    if(rapnetValue){
        return rapnetValue.toFixed(0)
    }else{
        return '';
    }
    return rapnetValue;
}

//格式化全深比
function DepthFormat(rapnetValue) {
    if(rapnetValue){
        return rapnetValue.toFixed(1)
    }else{
        return '';
    }
    return rapnetValue;
}

//获取推荐名称
function getRecommend(){
	$.ajax({
		url: "/Team/GetRecommend",//提交地址
		type: "POST",//提交方式
		contentType: "application/json; charset=utf-8",
		success: function (result) {
			var result = eval('(' + result + ')');//eval()解析单个json对象
			var html = [];
			var htmlList=[];
			$('#recommend_body').html('');
			$('#recommend_form').html('');
			if (result.msgcode == true) {

				recommendNum = result.msginfo.length + 1;

				var $remommend; //单个修改推荐显示下拉框
				var $searchTag=[]; //筛选
				$remommend = '<option value="0"></option>'
				for (var i = 0; i < result.msginfo.length; i++) {
					$remommend += '<option value="' + result.msginfo[i].ShortTag + '">' + _(result.msginfo[i].RecommendName) + '</option>';
					if(result.msginfo[i].FlagTag == 1 || result.msginfo[i].FlagTag == "1") {
						$searchTag.push([
							'<a href="#" data-value_tag="' + result.msginfo[i].ShortTag + '"> ' + _(result.msginfo[i].RecommendName) + ' </a>'
						].join(''))
					}
				}

				$("#form_Tag").html($remommend);
				$('#search_status_box .search_tag').append($searchTag.join(''));
				//单个修改推荐显示下拉框end 筛选end
				htmlList.push([
					'<div class="form-group" style="height:15px;margin-left:72px">',
					'<label for="rmb" class="form_i_qq">取消推荐<input type="radio" name="Recommend" style="margin-left:17px"  value="0"  /></label>',
					'</div>'
				].join(''));
				if (result.msginfo.length > 0) {
					for (var i = 0; i < result.msginfo.length; i++) {
						var row = result.msginfo[i];
						//修改 推荐 start
						html.push([
							'<tr style="color:#555">',
							'<td>'+row.RecommendName+'</td>',  //推荐
							'<td>'+row.ShortTag+'</td>',  //排序
							'<td>'+formatTag(row.FlagTag)+'</td>',  //启用
							'<td><span class="modify edit_btn_tag" data-id="'+row.ID+'" data-Recommend="'+row.RecommendName+'" data-ShortTag="'+row.ShortTag+'" data-FlagTag="'+row.FlagTag+'">编辑</span></td>',
							'</tr>'
						].join(''));
						//修改 推荐 end

						//确定推荐 设置 start
						if(row.FlagTag == 1 || row.FlagTag == "1"){
							htmlList.push([
								'<div class="form-group" style="height:15px;margin-left:100px">',
								'<label for="rmb" class="form_i_qq">' + row.RecommendName + '<input type="radio" name="Recommend" style="margin-left:15px" data-id="' + row.ID + '" data-Recommend="' + row.RecommendName + '" value="' + row.ShortTag + '"  /></label>',
								'</div>'
							].join(''));
						}
						//确定推荐 设置 end

					}
				}


			}else {
				recommendNum=1;
				html.push([
					'<tr>',
					'<td style="color:red" colspan="13">请先设置推荐名称</tds>',
					'</tr>'
				].join(''));

				htmlList.push([
					'<div class="form-group" style="height:28px;margin-left:15%">',
					'<label for="rmb" class="form_i_qq" style="color:red">请先设置推荐名称</label>',
					'</div>'
				].join(''));
			}
			$("#recommend_body").append(html.join('')); //推荐
			$("#recommend_form").append(htmlList.join('')); //设置
			inputChecked();
		}
	});
}

//推荐选中
function inputChecked() {
	var inventorylistCb = $("#stock_body .check_list_box span.selected");
	if(inventorylistCb.length==1){
		var valTag=inventorylistCb.attr("data-Tag");
		$("#recommend_form input[value="+valTag+"]").attr("checked",true);
	}else{
		$("input[name='Recommend']").prop("checked",false);
		$("#recommend").val('');
	}
}
//修改推荐
function mobileDia(){
	var Url=''
	var param={};
	param.UserID=UserID;
	if($("#remember_recommend").prop("checked")){
		param.FlagTag =1
	}else{
		param.FlagTag =0
	}
	if($('#recommend').val()!=''){
		param.RecommendName=$('#recommend').val();
	}else{
		alertMsgBox('推荐内容不能为空');
		return false;
	}
	if($('#recommend').attr('data-id')!=''){
		param.ShortTag=Number($("#recommend").attr('data-shorttag'));
		Url="/Team/ModifyRecommend";
		param.ID=$('#recommend').attr('data-id');
	}else {
		param.ShortTag=recommendNum;
		Url="/Team/AddRecommend";
	}

	$.ajax({
		url: Url,//提交地址
		type: "POST",//提交方式
		data: JSON.stringify(param),
		contentType: "application/json; charset=utf-8",
		success: function (result) {
			var _result = eval('(' + result + ')');//eval()解析单个json对象
			$("#search_status_box .search_tag").html('');
			if (_result.msgcode==true) {
				myApp.alert(_(_result["msginfo"]));
				$('#recommend').attr('data-id','');
				$('#recommend').val('');
				$('.addRecommend').val('添加');
				getRecommend();
			} else {
				myApp.alert(_(_result["msginfo"]));
			}
		}
	});

}

//是否格式化
function formatTag(tagVal){
	if(tagVal == 1 || tagVal == "1"){
		return '是';
	}else if(tagVal == 0 || tagVal == "0"){
		return '否';
	}else{
		return tagVal;
	}
}

//退点格式化
function DiscountReturnFormat(val){
	    if(val == null){
		       return '-' ;
		    }
	    return val.toFixed(3);
}



